package com.yl.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yl.auth.entity.Chuangweigenghuanshenpi;
import com.yl.auth.model.entity.Cwgenghuan;
import com.yl.auth.model.entity.Laoren;
import com.yl.auth.service.ChuangweigenghuanshenpiService;
import com.yl.auth.service.CwgenghuanService;
import com.yl.auth.service.LaorenService;
import com.yl.common.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.activiti.engine.*;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author 王庆梁
 * @datetime 2023/7/13 19:04
 * @description 类对象
 */
@RestController
@RequestMapping("/admin/auth/huligenghuanactivti")
@Api(tags = "审批管理-床位更换审批")
public class ChuangWeiGengHuanShenPiActivtiController {
    @Resource
    private RepositoryService repositoryService;  //部署流程

    @Resource
    private RuntimeService runtimeService;   //启动一个流程实例

    @Resource
    private TaskService taskService;    //处理任务

    @Resource
    private ChuangweigenghuanshenpiService chuangweigenghuanshenpiService;

    @Resource
    private LaorenService laorenService;

    @Resource
    private CwgenghuanService cwgenghuanService;

    @ApiOperation(value = "部署流程")
    @GetMapping("/deployProcess")
    public Result deployProcess(){
        //流程部署
        Deployment deploy = repositoryService.createDeployment()
                .addClasspathResource("process/chuangweigenghuan.bpmn20.xml")
                .addClasspathResource("process/chuangweigenghuan.png")
                .name("床位更换审批流程")
                .deploy();
        System.out.println(deploy.getId());
        System.out.println(deploy.getName());
        return Result.ok();
    }

    @GetMapping("/get/{name}")
    @ApiOperation(value = "查看当前个人待执行的任务")
    public Result get(@PathVariable @ApiParam("任务名") String name){
        List<Task> list = taskService.createTaskQuery()
                .taskAssignee(name)   //只查询该任务负责人的任务
                .list();
        for (Task task : list) {
            System.out.println("流程实例id:"+task.getProcessInstanceId());
            System.out.println("任务id：" + task.getId());
            System.out.println("任务负责人：" + task.getAssignee());
            System.out.println("任务名称：" + task.getName());
            System.out.println("业务id：" + task.getBusinessKey());
            System.out.println("----------------------------------------["+chuangweigenghuanshenpiService.getById(task.getBusinessKey()));
        }
        return Result.ok();
    }
    //开启审批流程
    @GetMapping("/kaiqi/{name}/{id}")
    @ApiOperation(value = "开启审批流程")
    public Result startUpProcess(@PathVariable @ApiParam("审批人名") String name,@PathVariable @ApiParam("任务id") String id) {
        Map<String,Object> variable = new HashMap<>();
        variable.put("name",name);
        //创建流程实例，我们需要知道流程定义的key
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("chuangweigenghuan",id,variable);
        //输出实例的相关信息
        System.out.println("流程定义id"+processInstance.getProcessDefinitionId());
        System.out.println("流程实咧id:"+processInstance.getId());
        System.out.println("当前活动id:"+processInstance.getActivityId());
        return Result.ok();
    }
    @GetMapping("/completTask/{name}")
    @ApiOperation(value = "处理当前任务")
    public Result completTask(@PathVariable String name){
        List<Task> task = taskService.createTaskQuery()
                .taskAssignee(name)  //要查询的负责人
                .list();//返回一条
        //完成任务，参数：任务id
        for (Task task1 : task) {
            taskService.setVariable(task1.getId(), "result", 0);
            taskService.complete(task1.getId());
        }

        return Result.ok();
    }

    @GetMapping("/getById/{id}")
    @ApiOperation(value = "通过老人id获取老人姓名")
    public Result getById(@PathVariable Long id) {
        String name = laorenService.get(id);
        return Result.ok(name);
    }

    @PostMapping("/fillIn/{laorenId}/{name}")
    @ApiOperation(value = "添加审批表")
    public Result fillIn(@RequestBody Chuangweigenghuanshenpi chuangweigenghuanshenpi,@PathVariable Long laorenId,@PathVariable String name) {
        Cwgenghuan cwgenghuan = cwgenghuanService.getById(laorenId);
        chuangweigenghuanshenpi.setLaorenId(cwgenghuan.getLrId());
        chuangweigenghuanshenpi.setName(name);
        chuangweigenghuanshenpi.setCreateTime(LocalDateTime.now());
        chuangweigenghuanshenpiService.save(chuangweigenghuanshenpi);
        return Result.ok();
    }

    @GetMapping("/getXiuGaiZhuangTai/{id}")
    @ApiOperation(value = "流程结束时修改床位的状态只是在成功时")
    public Result getXiuGaiZhuangTai(@PathVariable Integer id) {
        //根据id获取指定的床位更换的数据
        Cwgenghuan cwgenghuan = cwgenghuanService.getById(id);
        cwgenghuan.setZhuangtai(2);
        cwgenghuanService.updateById(cwgenghuan);
        //根据床位更换的老人外键获取到老人的数据
        Laoren laoren = laorenService.getById(cwgenghuan.getLrId());
        laoren.setBedId(cwgenghuan.getCwsId());
        laoren.setRoomId(cwgenghuan.getFjsId());
        laorenService.updateById(laoren);
        return Result.ok(cwgenghuan);
    }

    @GetMapping("/getURL/{id}")
    @ApiOperation(value = "回显床位更换审批数据")
    public Result getURL(@PathVariable Long id) {
        Cwgenghuan cwgenghuan = cwgenghuanService.getById(id);
        LambdaQueryWrapper<Chuangweigenghuanshenpi> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Chuangweigenghuanshenpi::getLaorenId,cwgenghuan.getLrId());
        Chuangweigenghuanshenpi chuangweigenghuanshenpi = chuangweigenghuanshenpiService.getOne(wrapper);
        String[] split = chuangweigenghuanshenpi.getName().split(",");
        String str = "";
        String str2 = "";
        String str3 = "";
        for (int i=0;i<split.length;i++){
            str = split[0];
            str2 = split[1];
            str3 = split[2];
        }
        chuangweigenghuanshenpi.setXname(str);
        chuangweigenghuanshenpi.setCname(str2);
        chuangweigenghuanshenpi.setYname(str3);
        return Result.ok(chuangweigenghuanshenpi);
    }

    @GetMapping("/getXiuJuJue/{id}")
    @ApiOperation(value = "审批人点击审批拒绝的话修改床位更换状态")
    public Result getXiuJuJue(@PathVariable Integer id){
        //根据id获取到床位更换的数据
        Cwgenghuan cwgenghuan = cwgenghuanService.getById(id);
        cwgenghuan.setZhuangtai(1);
        cwgenghuanService.updateById(cwgenghuan);
        return Result.ok();
    }

    @GetMapping("/ReTask/{name}")
    public Result RejectTask(@PathVariable String name){
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        List<Task> task = taskService.createTaskQuery()
                .processDefinitionKey("chuangweigenghuan")
                .taskAssignee(name)
                .list();
        Authentication.setAuthenticatedUserId(name);
        //异常结束
        for (Task task1 : task) {
            taskService.setVariable(task1.getId(),"result",1);
            taskService.complete(task1.getId());
        }
        return Result.ok();
    }
    @GetMapping("/getYuanYin/{id}")
    @ApiOperation(value = "审批拒绝回显原因")
    public Result getYuanYin(@PathVariable Integer id){
        Cwgenghuan cwgenghuan = cwgenghuanService.getById(id);
        LambdaQueryWrapper<Chuangweigenghuanshenpi> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Chuangweigenghuanshenpi::getLaorenId,cwgenghuan.getLrId());
        Chuangweigenghuanshenpi chuangweigenghuanshenpi = chuangweigenghuanshenpiService.getOne(wrapper);
        return Result.ok(chuangweigenghuanshenpi);
    }

    @GetMapping("/removeJuJue/{id}")
    @ApiOperation(value = "编辑的时候删除表中添加的数据根据id")
    public Result removeJuJue(@PathVariable Integer id){
        Cwgenghuan cwgenghuan = cwgenghuanService.getById(id);
        Optional<Cwgenghuan> cwgenghuanOptional = Optional.ofNullable(cwgenghuan);
        Integer lrId = cwgenghuanOptional.map(Cwgenghuan::getLrId).orElse(null);
        LambdaQueryWrapper<Chuangweigenghuanshenpi> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Chuangweigenghuanshenpi::getLaorenId,lrId);
        chuangweigenghuanshenpiService.remove(wrapper);
        return Result.ok();
    }

}
